<template>
  <a-drawer v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'" draggable @before-ok="save" @close="reset">
    <fieldset>
      <legend>基础信息</legend>
      <GiForm ref="formRef" v-model="form" :columns="columns" />
    </fieldset>
    <fieldset>
      <legend>联系人</legend>
      <a-space direction="vertical" fill>
        <a-button type="primary" @click="addRow" style="margin-top: 16px">
          新增
        </a-button>
        <a-table :data="contactsData" :columns="contactsColumns" :pagination="false" bordered>
          <template #name="{ record, rowIndex }">
            <a-input v-model.trim="record.name" allow-clear="false" />
          </template>
          <template #phone="{ record, rowIndex }">
            <a-input v-model.trim="record.phone" />
          </template>
          <template #post="{ record, rowIndex }">
            <a-row>
              <a-col :span="18">
                <a-input v-model.trim="record.post" allow-clear="false" />
              </a-col>
              <a-col :span="1">
              </a-col>
              <a-col :span="4">
                <a-button @click="deleteRow(rowIndex)">
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-col>
            </a-row>
          </template>

        </a-table>
      </a-space>
      <br />
    </fieldset>
  </a-drawer>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getProducerRecords, addProducerRecords, updateProducerRecords } from '@/apis/asset/producer/records'
  import type { ColumnItem, GiForm } from '@/components/GiForm'
  import type { TableInstanceColumns, GiTable } from '@/components/GiTable'

  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'

  interface TableData {
    name: string;
    phone: string;
    post: number;
  }

  const emit = defineEmits < {
    (e: 'save-success'): void
  }> ()

  const { width } = useWindowSize()

  const dataId = ref('')
  const visible = ref(false)
  const isUpdate = computed(() => !!dataId.value)
  const title = computed(() => (isUpdate.value ? '修改厂商' : '新增厂商'))
  const formRef = ref < InstanceType < typeof GiForm >> ()

  const [form, resetForm] = useResetReactive({
    // todo 待补充

  })

  // 联系人
  const contactsData = ref < TableData[] > ([]);

  const columns: ColumnItem[] = reactive([
    {
      label: '厂商名称',
      field: 'name',
      type: 'input',
      span: 24,
      rules: [{ required: true, message: '请输入厂商名称' }],
      props: {
        maxLength: 50,
      },
    },
    {
      label: '地址',
      field: 'address',
      type: 'input',
      span: 24,
    },
    {
      label: '厂商描述',
      field: 'description',
      type: 'textarea',
      span: 24,
      props: {
        maxLength: 250
      },
    },
  ])

  // 重置
  const reset = () => {
    contactsData.value = [];
    formRef.value?.formRef?.resetFields()
    resetForm()
  }

  const contactsColumns = [
    {
      title: '姓名',
      dataIndex: 'name',
      slotName: 'name'
    },
    {
      title: '电话',
      dataIndex: 'phone',
      slotName: 'phone'
    },
    {
      title: '职位',
      dataIndex: 'post',
      slotName: 'post'
    }
  ];

  // 删除联系人
  const deleteRow = (index: number) => {
    contactsData.value.splice(index, 1);
  };

  // 添加联系人
  const addRow = () => {
    const newRow: TableData = {
      name: '',
      phone: '',
      post: ''
    };
    contactsData.value.push(newRow);
  };

  // 保存
  const save = async () => {
    form.contacts = JSON.stringify(contactsData.value);
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
      if (isUpdate.value) {
        await updateProducerRecords(form, dataId.value)
        Message.success('修改成功')
      } else {
        await addProducerRecords(form)
        Message.success('新增成功')
      }
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }

  // 新增
  const onAdd = async () => {
    reset()
    dataId.value = ''
    visible.value = true
  }

  // 修改
  const onUpdate = async (id: string) => {
    reset()
    dataId.value = id
    const { data } = await getProducerRecords(id)
    contactsData.value = data.contacts ? JSON.parse(data.contacts) : contactsData.value
    Object.assign(form, data)
    visible.value = true
  }

  defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss">
  fieldset {
    padding: 15px 15px 0 15px;
    margin-bottom: 15px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }

  fieldset legend {
    color: rgb(var(--gray-10));
    padding: 2px 5px 2px 5px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }
</style>